package com.lemon.cloud.mybatis;

import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.creator.hikaricp.HikariDataSourceCreator;
import com.baomidou.dynamic.datasource.processor.DsProcessor;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.lemon.cloud.mybatis.config.ClearTtlDataSourceFilter;
import com.lemon.cloud.mybatis.config.DataSourceProperties;
import com.lemon.cloud.mybatis.config.JdbcDynamicDataSourceProvider;
import com.lemon.cloud.mybatis.config.LastParamDsProcessor;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * @author HuangDS
 */
@Configuration
@AllArgsConstructor
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@EnableConfigurationProperties(DataSourceProperties.class)
public class DynamicDataSourceAutoConfiguration {

    @Bean
    public DynamicDataSourceProvider dynamicDataSourceProvider(DefaultDataSourceCreator defaultDataSourceCreator,DataSourceProperties properties) {
        return new JdbcDynamicDataSourceProvider(defaultDataSourceCreator,properties);
    }

    @Bean
    public DsProcessor dsProcessor() {
        return new LastParamDsProcessor();
    }

    /**
     * 默认数据源创建器
     * @param hikariDataSourceCreator Hikari数据源创建器
     * @return 默认数据源创建器
     */
    @Bean
    public DefaultDataSourceCreator defaultDataSourceCreator(HikariDataSourceCreator hikariDataSourceCreator) {
        DefaultDataSourceCreator defaultDataSourceCreator = new DefaultDataSourceCreator();
        List<DataSourceCreator> creators = new ArrayList<>();
        creators.add(hikariDataSourceCreator);
        defaultDataSourceCreator.setCreators(creators);
        return defaultDataSourceCreator;
    }

    @Bean
    public ClearTtlDataSourceFilter clearTtlDsFilter() {
        return new ClearTtlDataSourceFilter();
    }
}
